//
//  LRHomeTableVC.swift
//  WeiboX
//
//  Created by admin on 30/11/2016.
//  Copyright © 2016 iOS_Objective-C. All rights reserved.
//

import UIKit
import SnapKit

private let homeCellID = "homeCellID"

class LRHomeTableVC: LRVisitorTableVC {
	
	// 用于请求主页数据 viewModel
	fileprivate var homeStatusVM = LRHomeStatusVM()
	// 下拉刷新
	 // Command failed due to signal: Segmentation fault: 11
	fileprivate lazy var pullDownV: LRRefreshControl = {
		let refreshControl = LRRefreshControl()
		
		refreshControl.addTarget(self, action: #selector(pullDownAndLoad), for: .valueChanged)
		
//		refreshControl.isHidden = true
		return refreshControl
	}()
	// 上拉刷新
	fileprivate var pullUpV: UIActivityIndicatorView = {
		let activityIndicatorV = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
		activityIndicatorV.backgroundColor = .red
		activityIndicatorV.backgroundColor = .green
		return activityIndicatorV
	}()
	
	fileprivate var tips: UILabel = {
		let label = UILabel(fontSize: 12, textColor: .white)
		label.backgroundColor = .orange
		label.textAlignment = .center
		label.isHidden = true
		
		return label
	}()
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		if !isLogin {
			visitorV?.updateWidgetLayout(imgName: nil, lableTxt: nil)
		} else {
			setupUI()
			loadData()
		}
//		refreshControl?.addTarget(self, action: #selector(pullDownAndLoad), for: .valueChanged)
	}
	
	@objc private func pullDownAndLoad() {
		print("下拉刷新")
		loadData()
	}
	
	// 结束刷新
	private func endRefreshing() {
		pullDownV.endRefreshing()
		pullUpV.stopAnimating()
	}
	
	fileprivate func loadData() {
		homeStatusVM.loadData(isUp: pullUpV.isAnimating) { (isSuccess, message) in
			
			if self.pullUpV.isAnimating == false {
				self.tipsAnimation(message: message)
			}
//			self.pullDownV.isHidden = false
			
			
			// 停止加载更多
			self.endRefreshing()
			
			if isSuccess {
				self.tableView.reloadData()
//				self.pullDownV.isHidden = true
			}
		}
	}
	
	private func setupUI() {
		if let nav = self.navigationController {
			nav.view.insertSubview(tips, belowSubview: nav.navigationBar)
			
			tips.frame = CGRect(x: 0, y: nav.navigationBar.frame.maxY - 35, width: ScreenWidth, height: 35)
		}
		
		setupTableView()
	}
	
	private func setupTableView() {
		tableView.register(LRStatusTableVCell.self, forCellReuseIdentifier: homeCellID)
		
		tableView.separatorStyle = .none
		
		// tableView 自适应行高
		tableView.rowHeight = UITableViewAutomaticDimension
		tableView.estimatedRowHeight = 200
		
		
		tableView.addSubview(pullDownV)
		tableView.tableFooterView = pullUpV
	}
	
	// tips 的位移动画
	private func tipsAnimation(message: String) {
		if tips.isHidden == false {
			// 正在执行动画, 直接 return
			return
		}
		
		tips.isHidden = false
		tips.text = message
		
		UIView.animate(withDuration: 1, animations: {
			self.tips.transform = CGAffineTransform(translationX: 0, y: self.tips.height)
		}) { (_) in
			UIView.animate(withDuration: 1, animations: { 
				self.tips.transform = CGAffineTransform.identity
			}, completion: { (_) in
				self.tips.isHidden = true
//				self.pullDownV.isHidden = true
			})
		}
	}
	
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


// MARK: - 数据源和代理
extension LRHomeTableVC {
	// MARK: - Table view data source
	override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		// #warning Incomplete implementation, return the number of rows
		return homeStatusVM.statusList.count
	}
	
	override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
		let cell = tableView.dequeueReusableCell(withIdentifier: homeCellID, for: indexPath) as! LRStatusTableVCell
		
		cell.statusVM = homeStatusVM.statusList[indexPath.row]
		
		return cell
	}
	
	// MARK: - Table view delegate
	override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
		if indexPath.row == homeStatusVM.statusList.count - 1 && !pullUpV.isAnimating {
			print("已经滚动到最后一个 cell 了")
			pullUpV.startAnimating()
			
			
			loadData()
		}
	}
}
